////////////////////////////////////////////////////////////////////////////////
///                        ClockRealTime.C                         ///
///                                                                             ///
///       Contents: Firmware for Real Time Clock  ///
///       Programmer : Truong Van Hieu                 ///
///       Date    : 2009/08/10                                 ///
///                                                                           ///
///                                                                           ///
///                                                                          ///
///                                                                          ///
////////////////////////////////////////////////////////////////////////////////

#include <18f4580.h>
#include <Define18F458.h>
#device  *=16 ADC=10 HIGH_INTS=TRUE
#FUSES NOWDT,HS,NODEBUG, NOBROWNOUT, NOLVP
#use delay(clock=20000000)
//#use Fast_IO(b)
#include <DefineClockReadTime.h>
#include <NumberCode.h>
#use i2c(master,sda=device_SDA, scl=device_SCL,slow)
#use rs232(baud=9600,xmit=PIN_C6,rcv=PIN_C7,errors)
#include <74595Modified.c>
#include <Ds1307.c>
#include <24256.c>
#include <external_eeprom.c>


#define NO_PRESS 0
#define BUTTON_A 1
#define BUTTON_B 2

#define RunRealTime 0
#define SettingTime 1

//--------------------Khai Bao Hang------------------------------//
const int sl_ad_org = 0;
const int phut_ad_org = 50;
const int giay_ad_org = 100;

const int numberLedDisplay = 4;

//--------------------Khai Bao Bien------------------------------//
int temp=0;
int1 sta=0;
int1 flag=0;

int key_press=0;

int mode=0;
int submode=0;

int1 key1_press=0;
int1 key2_press=0;
int1 key3_press=0;
int1 key4_press=0;


int1 key1e=1;
int1 key2e=1;
int1 key3e=1;
int1 key4e=1;

int1 DE=0;
int1 general=0;
int1 back_all=0;
int1 back1=0;
int1 count_enable=1;



int bai=0;
int number=0;
int gio, phut, giay;
int scount=0;
int mcount=0;
int slan;
int pt,st,loop;
int bt=0;

int order[20];
int M_array[20];
int S_array[20];
int test = 0;

//--------------------Khai Bao Ham -------------------======-----------//
void init();
void bip(int lan);
int getKeyHit();
void nextMode();
void readKey();
void changeHour();
void changeMinute();
void turn_off_led();
void turn_on_led();
void display( int v1, int v2, int v3, int style );
void init_data();
void load_data();
void save_data(int val1,int val2,int val3,int val4);
void set_start_data();
void set_data( int &loopset, int &ptset, int &stset, int submode );
void dis_time();
void run_system();
//-----------End Khai Bao Ham------------------------------------------//

//----Ngat time0------------------------------------------------------//
#INT_RTCC
TIMER0_isr()
{
   flag = 1;
   if (count_enable)
   {
      number++;
      scount++;
      if (scount>=60)
      {
         scount=0;
         mcount++;
         if (mcount>=60) {mcount=0;}
      }
   }

   DE=!DE;
   sta=!sta;
   st_led(sta);
   set_RTCC(0xff);
}

//----Ngat ngoai---------------------------------------------------//
#INT_EXT HIGH
void ext_isr()
{
   key_press = 0;//reset

   if (input(key1))
   {
      key_press = BUTTON_A;
   }
   else
   {
      if (input(key2))
      {
         key_press = BUTTON_B;
      }
      else
      {
         key_press = NO_PRESS;
      }
   }
}

//-----------------------------------------------------------------//
//                                                                 //
//                      KHAI BAO CHUONG TRINH CON                  //
//                                                                 //
//-----------------------------------------------------------------//
void init()
{
   set_tris_b(0xff);
   set_tris_d(0x00);
   trisC0=0;
   trisc1=0;
   trisc2=0;
   trisc5=0;
   COI(0);
   //trisa4=1;
   //set_timer0(255);
   set_RTCC(255);
   setup_timer_0 (RTCC_EXT_H_TO_L|RTCC_8_bit|RTCC_DIV_1);
   enable_interrupts(INT_RTCC);
   enable_interrupts(INT_EXT);
   EXT_INT_EDGE(L_TO_H);
   loa(1);
   WP(1);
}

//----Tao am thanh-------------------------------------------------------//
void bip(int lan)
{
   int i;
   for (i=0; i<lan; i++)
   {
      loa(0);
      COI(1);
      delay_ms(80);
      loa(1);
      COI(0);
      delay_ms(80);
   }
}

//----Nhan phim---------------------------------------------------------//
int getKeyHit()
{
      return   key_press;
}

//----Change mode---------------------------------------------------------//
void nextMode()
{
      switch( mode )
      {
         case RunRealTime:
               {
                  mode = SettingTime;
                  submode = 0;
               }
               break;

         case SettingTime:
               {
                  switch( submode )
                  {
                     //submode chinh gio
                     case 0:
                           {
                              submode++;
                           }
                           break;

                     //submode chinh phut
                     case 1:
                           {
                              mode = RunRealTime;
                              submode = 0;
                           }
                           break;
                  }
               }
               break;
      }
}

//----Read key---------------------------------------------------------//
void readKey()
{
   if( getKeyHit() == BUTTON_A )
   {
      nextMode();
   }
}


//----Change Hour---------------------------------------------------------//
void changeHour()
{

}

//----Change Minute------------------------------------------------------//
void changeMinute()
{

}

//----Tat led----------------------------------------------------------//
void turn_off_led()
{
   int buf[numberLedDisplay];
   int i;
   for (i=0; i<numberLedDisplay; i++)
   {
      buf[i] = NC[0];
   }
   write_expanded_outputs(buf);
}

//----Bat led----------------------------------------------------------//
void turn_on_led()
{
   int buf[numberLedDisplay];
   int i;
   for (i=0; i<numberLedDisplay; i++)
   {
      buf[i] = NC[10];
   }
   write_expanded_outputs(buf);
}

//----Hien thi--------------------------------------------------------//
void display( int v1, int v2, int v3, int style )
{
   int buf[4];
   int chuc1, dv1, chuc2, dv2;

   chuc1 = v1/10;
   dv1 = v1%10;

   chuc2 = v2/10;
   dv2 = v2%10;
   //--------------------------
   switch( style )
   {
      case 0:
         {
            buf[0]=NC[chuc1]; buf[1]=NC[dv1];
            buf[2]=NC[chuc2]; buf[3]=NC[dv2];

            if( v3 % 2 == 0 )
            {
               buf[3] = (buf[3] | 0b00000001);
            }
         }
         break;
      case 1:
         {
            if (DE)
            {
               buf[0]=NC[chuc1]; buf[1]=NC[dv1];
            }
            else
            {
               buf[0]=0; buf[1]=0;
            }
            buf[2]=NC[chuc2]; buf[3]=NC[dv2];
         }
         break;
      case 2:
         {
            if (DE)
            {
               buf[2]=NC[chuc2]; buf[3]=NC[dv2];
            }
            else
            {
               buf[2]=0; buf[3]=0;
            }
            buf[0]=NC[chuc1]; buf[1]=NC[dv1];
         }
         break;
      default:
         {
            buf[0]=NC[chuc1]; buf[1]=NC[dv1];
            buf[2]=NC[chuc2]; buf[3]=NC[dv2];
         }
         break;
   }

   write_expanded_outputs(buf);
}

//----Init----------------------------------------------------------------//
void init_data()
{
   int i;
   for (i=0;i<20;i++)
   {
      order[i]=2;
      M_array[i]=1;
      S_array[i]=i;
   }
}

//----Load data----------------------------------------------------------//
void load_data()
{
   int i;
   for ( i=0; i<20; i++ )
   {
      order[i]=read_ext_eeprom(sl_ad_org+i);
      M_array[i]=read_ext_eeprom(phut_ad_org+i);
      S_array[i]=read_ext_eeprom(giay_ad_org+i);
   }
}

//----Save data---------------------------------------------------------//
void save_data(int val1,int val2,int val3,int val4)
{
   WP(0);
   write_ext_eeprom(sl_ad_org+val1,val2);   //luu so lan
   write_ext_eeprom(phut_ad_org+val1,val3); //luu phut
   write_ext_eeprom(giay_ad_org+val1,val4); //luu giay
   WP(1);
   order[val1]=val2;
   M_array[val1]=val3;
   S_array[val1]=val4;
}

//----Set start---------------------------------------------------------//
void set_start_data()
{
   int i;
   init_data();
   for (i=0;i<20;i++)
   {
      save_data(i,order[i],M_array[i],S_array[i]);
   }
}

//----Set data---------------------------------------------------------//
void set_data( int &loopset, int &ptset, int &stset, int submode )
{
   general = 1;

   while ( mode == SettingTime )
   {
      switch( submode )
      {
         //chinh gio
         case 0:
               {
                  if( getKeyHit() == BUTTON_B )//tang gio
                  {
                     loopset++;
                     if( loopset > 23) loopset=0;
                  }
                  else
                  {
                     //display( loopset, ptset, stset, 1 );
                  }
               }
               break;
         //chinh phut
         case 1:
               {
                  if( getKeyHit() == BUTTON_B )//tang phut
                  {
                     ptset++;
                     if( ptset > 59) ptset=0;
                  }
                  else
                  {
                     //display( loopset, ptset, stset, 2 );
                  }
               }
               break;
      }
   }
   //save time-------------------------------
   if (gio<24 && phut<60 && giay<60 )
   {
      ds1307_set_time( gio, phut, giay);
      bip(3);
   }
   general=0;
}

//----Display time----------------------------------------------------//
void dis_time()
{
   if ( flag )
   {
      ds1307_get_time( gio, phut, giay );
      if( (phut == 0) && (giay == 0) )
      {
         bip( gio );
      }
      display( gio, phut, giay, 0 );
      flag = 0;
   }
}


//----Run RTC-- --------------------------------------------------//
void run_RTC()
{
	dis_time();
}

//----Run System-- ---------------------------------------------//
void run_system()
{
	while (1)
	{
      //---test cac ham-------------------------------
      if(test)
      {
         /*
         //test loa------------------------ 
         bip(1);
         turn_on_led();
         delay_ms(1000);

         bip(1);
         turn_off_led();
         delay_ms(1000);
         */
         //dis_time();
         /*
         //test hien thi------------------------
         int i, giay11, phut11, gio11;
         for(i=0; i <= 59; i++)
         {
            giay11 = i;
            gio11 = i;
            phut11 = i;
            display( gio11, phut11, giay11, 0 );
            //bip(1);
            delay_ms(1000);
         }
         */
         
         //test loa------------------------
         //ds1307_set_time( 20, 59, 00);
         ds1307_get_time( gio, phut, giay );
         display( gio, phut, giay, 0 );

         continue;
      }
      //end test test--------------------------------

      //---read key---------------------------------------------------
      ///readKey();

      //---process---------------------------------------------------
		switch ( mode )
		{
         //chay thoi gian thuc------------------------
			case RunRealTime:
               {
                  dis_time();
               }
               break;
         //hieu chinh thoi gian----------------------
			case SettingTime:
               {
                  switch( submode )
                  {
                     //chinh gio----------------
                     case 0:
                     case 1:
                           {
                                set_data( gio, phut, giay, submode );
                           }
                           break;
                  }
               }
               break;
         //------------------------------------------
		}
	}
}


//-----------------------------------------------------------------//
//                                                                 //
//                      CHUONG TRINH CHINH                         //
//                                                                 //
//-----------------------------------------------------------------//
void main()
{
	init();
	ds1307_init();
	turn_off_led();
	enable_interrupts(GLOBAL);
   //ds1307_set_time( 10, 41, 00);
	bip(1);
   delay_ms(1000);

   test = 0;//test
	run_system();
	while (1);
}
//----End -- ---------------------------------------------//
